//
//  AddGoodsTableViewController.m
//  帮惠Mall
//
//  Created by reew on 2017/9/22.
//  Copyright © 2017年 reew. All rights reserved.
//

#import "AddGoodsTableViewController.h"
#import "GoodsStandardsTableViewController.h"
#import <SVProgressHUD.h>
#import "GoodsStandardsTableViewController.h"
#import "TagViewController.h"
#import <ActionSheetCustomPicker.h>
#import <MJExtension.h>
#import <AFNetworking.h>
#import "CommonUtils.h"
#import <SVProgressHUD.h>
#import "Admin.h"
#import "AddCompanyTableViewController.h"
#import "System.h"
#import "Account.h"
#import "InputViewController.h"
typedef void(^MyBlock)(NSString *address,NSArray *selections);
@interface AddGoodsTableViewController ()<UITableViewDelegate,UITableViewDataSource,ActionSheetCustomPickerDelegate>
//地址选择器
@property (nonatomic,strong) NSArray *addressArr; // 解析出来的最外层数组
@property (nonatomic,strong) NSArray *provinceArr; // 省
@property (nonatomic,strong) NSArray *countryArr; // 市
@property (nonatomic,strong) NSArray *districtArr; // 区
@property (nonatomic,assign) NSInteger index1; // 省下标
@property (nonatomic,assign) NSInteger index2; // 市下标
@property (nonatomic,assign) NSInteger index3; // 区下标
@property (nonatomic,strong) ActionSheetCustomPicker *picker; // 选择器
@property (nonatomic,strong) NSArray *selections; //!< 选择的三个下标
@property (nonatomic,copy) NSString *pushAddress; //!< 展示的地址
@property (nonatomic,strong) NSString *city;
@property (nonatomic,strong) NSString *region;
@property (nonatomic,strong) NSString *province;
@property (nonatomic,copy) MyBlock myBlock; //!< 回调地址的block

@property (nonatomic,strong) NSString *fahuodi;
@end

@implementation AddGoodsTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tabBarController.tabBar.hidden = YES;
    [self setUpAddressView];
    [self setupNav];
    [self setUpInfo];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setUpInfo];
}
- (void)setUpInfo{
    _nameCell.detailTextLabel.text = _name;
    _intriductionCell.detailTextLabel.text = _introduction;
    _serviceCell.detailTextLabel.text = _serviceDescription;
    _priceCell.detailTextLabel.text = _price;
    _logisticsPriceCell.detailTextLabel.text = _logisticsPrice;
    _couponCell.detailTextLabel.text = _coupon;
    _returnCell.detailTextLabel.text = _returnExpiration;
    _exchangeCell.detailTextLabel.text = _exchangeExpiration;
}
- (void)setupNav{
    UIBarButtonItem *rightItem= [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(save)];
    //    rightItem.tintColor = [UIColor blackColor];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
}
//提交商品信息
- (void)save{
    //判断信息是否填写完全
    if (_typeNo == nil){
        [SVProgressHUD setMaximumDismissTimeInterval:1];
        [SVProgressHUD showErrorWithStatus:@"请选择商品类目"];
    }else if(_name == nil||_name.length == 0){
        [SVProgressHUD setMaximumDismissTimeInterval:1];
        [SVProgressHUD showErrorWithStatus:@"请输入商品名称"];
    }else if (_introduction == nil||_introduction.length == 0){
        [SVProgressHUD setMaximumDismissTimeInterval:1];
        [SVProgressHUD showErrorWithStatus:@"请输入商品说明"];
        
    }else if (_price == nil||_price.length == 0){
        [SVProgressHUD setMaximumDismissTimeInterval:1];
        [SVProgressHUD showErrorWithStatus:@"请输入商品价格"];
    }else if (_logisticsPrice == nil||_logisticsPrice.length == 0){
        [SVProgressHUD setMaximumDismissTimeInterval:1];
        [SVProgressHUD showErrorWithStatus:@"请输入商品运费"];
    }else if (_fahuodi == nil||_fahuodi.length == 0){
        [SVProgressHUD setMaximumDismissTimeInterval:1];
        [SVProgressHUD showErrorWithStatus:@"请选择发货地址"];
    }else if (_exchangeExpiration == nil ||_exchangeExpiration.length == 0){
        [SVProgressHUD setMaximumDismissTimeInterval:1];
        [SVProgressHUD showErrorWithStatus:@"请输入换货周期"];
    }else if (_returnExpiration == nil ||_returnExpiration.length == 0){
        [SVProgressHUD setMaximumDismissTimeInterval:1];
        [SVProgressHUD showErrorWithStatus:@"请输入退货周期"];
    }
    else{
        AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
        NSString *url = [kBaseURL stringByAppendingPathComponent:kAddGoods];
        [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            //参数必选：adminNo(根据企业管理员编号找到企业编号) typeNo(商品类型编号为最小子类型编号) name(商品名称) introduction(商品介绍) coupon(抵金卷, 默认为0.00) price(售价) logisticsPrice(快递费, 默认为0.00) returnExpiration(退货周期, 默认0不退货) exchangeExpiration(换货周期, 默认0不换货)
            //参数可选：tag(商品标签: 新品, 爆款 以英文逗号拼接) serviceDescription(服务说明用英文逗号连接) male(男性用品, 0选中, 1未选中) female(女性用品, 0选中, 1未选中) color(颜色以英文逗号拼接) size(尺寸以英文逗号拼接)
            NSString *adminNo = [Account sharedAccount].adminNo;
            if (adminNo != nil) {
                [formData appendPartWithFormData:[adminNo dataUsingEncoding:NSUTF8StringEncoding] name:@"adminNo"];
            }
            [formData appendPartWithFormData:[_typeNo dataUsingEncoding:NSUTF8StringEncoding] name:@"typeNo"];
            [formData appendPartWithFormData:[_name dataUsingEncoding:NSUTF8StringEncoding] name:@"name"];
            [formData appendPartWithFormData:[_introduction dataUsingEncoding:NSUTF8StringEncoding] name:@"introduction"];
            [formData appendPartWithFormData:[@"00.00" dataUsingEncoding:NSUTF8StringEncoding] name:@"coupon"];
            [formData appendPartWithFormData:[_price dataUsingEncoding:NSUTF8StringEncoding] name:@"price"];
            [formData appendPartWithFormData:[_logisticsPrice dataUsingEncoding:NSUTF8StringEncoding] name:@"logisticsPrice"];
            [formData appendPartWithFormData:[@"武汉" dataUsingEncoding:NSUTF8StringEncoding] name:@"dispatchAddress"];
            [formData appendPartWithFormData:[_returnExpiration dataUsingEncoding:NSUTF8StringEncoding] name:@"returnExpiration"];
            [formData appendPartWithFormData:[_exchangeExpiration dataUsingEncoding:NSUTF8StringEncoding] name:@"exchangeExpiration"];
            
            if (_tagStr == nil) {
                [formData appendPartWithFormData:[@"" dataUsingEncoding:NSUTF8StringEncoding] name:@"tag"];
            }else{
                [formData appendPartWithFormData:[_tagStr dataUsingEncoding:NSUTF8StringEncoding] name:@"tag"];
            }
            
            if (_serviceDescription == nil) {
                [formData appendPartWithFormData:[@"" dataUsingEncoding:NSUTF8StringEncoding] name:@"serviceDescription"];
            }else{
                [formData appendPartWithFormData:[_serviceDescription dataUsingEncoding:NSUTF8StringEncoding] name:@"serviceDescription"];
            }
            
            if (_color == nil) {
                [formData appendPartWithFormData:[@"" dataUsingEncoding:NSUTF8StringEncoding] name:@"color"];
            }else{
                
                [formData appendPartWithFormData:[_color dataUsingEncoding:NSUTF8StringEncoding] name:@"color"];
            }
            
            if (_size == nil) {
                [formData appendPartWithFormData:[@"" dataUsingEncoding:NSUTF8StringEncoding] name:@"size"];
            }else{
                [formData appendPartWithFormData:[_size dataUsingEncoding:NSUTF8StringEncoding] name:@"size"];
            }
            
        } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@",responseObject);
            NSString *result = responseObject[@"result"];
            NSString *message = responseObject[@"message"];
            [SVProgressHUD setMaximumDismissTimeInterval:1];
            if ([result integerValue] == 1) {
                [SVProgressHUD setMaximumDismissTimeInterval:1];
                [SVProgressHUD showSuccessWithStatus:message];
                [self skipVC:responseObject[@"goodsNo"]];
            }else{
                [SVProgressHUD setMaximumDismissTimeInterval:1];
                [SVProgressHUD showErrorWithStatus:message];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
            [SVProgressHUD setMaximumDismissTimeInterval:1];
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
        }];
    }
    
    
    
}
- (void)skipVC:(NSString *)goodsNo{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    AddCompanyTableViewController *vc = [sb instantiateViewControllerWithIdentifier:@"companyAuth"];
    vc.isShowDefault = YES;
    vc.skipType = @"uploadGoodsImage";
    vc.goodsNo =goodsNo;
    vc.title = @"添加商品图片";
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)showAddressView{
    self.picker = [[ActionSheetCustomPicker alloc]initWithTitle:@"选择地区" delegate:self showCancelButton:YES origin:self.view initialSelections:@[@(self.index1),@(self.index2),@(self.index3)]];
    self.picker.tapDismissAction  = TapActionSuccess;
    // 可以自定义左边和右边的按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 44, 44);
    [button setTitle:@"取消" forState:UIControlStateNormal];
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [button1 setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    button1.frame = CGRectMake(0, 0, 44, 44);
    [button1 setTitle:@"确定" forState:UIControlStateNormal];
    [self.picker setCancelButton:[[UIBarButtonItem alloc] initWithCustomView:button]];
    [self.picker setDoneButton:[[UIBarButtonItem alloc] initWithCustomView:button1]];
    
    //    [self.picker addCustomButtonWithTitle:@"再来一次" value:@(1)];
    [self.picker showActionSheetPicker];
    
}

- (void)setUpAddressView{
    
//    if (self.pushAddress) {
//        self.detailAddress.text = self.pushAddress;
//    }
    
    if ((self.selections == nil) ) {
        self.index1 = [self.selections[0] integerValue];
        self.index2 = [self.selections[1] integerValue];
        self.index3 = [self.selections[2] integerValue];
    }
    // 一定要先加载出这三个数组，不然就蹦了
    [self calculateFirstData];
}
- (void)loadFirstData
{
    // 注意JSON后缀的东西和Plist不同，Plist可以直接通过contentOfFile抓取，Json要先打成字符串，然后用工具转换
    NSString *path = [[NSBundle mainBundle] pathForResource:@"address" ofType:@"json"];
    NSLog(@"%@",path);
    NSString *jsonStr = [NSString stringWithContentsOfFile:path usedEncoding:nil error:nil];
    self.addressArr = [jsonStr mj_JSONObject];
    
    NSMutableArray *firstName = [[NSMutableArray alloc] init];
    for (NSDictionary *dict in self.addressArr)
    {
        NSString *name = dict.allKeys.firstObject;
        [firstName addObject:name];
    }
    // 第一层是省份 分解出整个省份数组
    self.provinceArr = firstName;
}


// 根据传进来的下标数组计算对应的三个数组
- (void)calculateFirstData
{
    // 拿出省的数组
    [self loadFirstData];
    
    NSMutableArray *cityNameArr = [[NSMutableArray alloc] init];
    // 根据省的index1，默认是0，拿出对应省下面的市
    for (NSDictionary *cityName in [self.addressArr[self.index1] allValues].firstObject) {
        
        NSString *name1 = cityName.allKeys.firstObject;
        [cityNameArr addObject:name1];
    }
    // 组装对应省下面的市
    self.countryArr = cityNameArr;
    //                             index1对应省的字典         市的数组 index2市的字典   对应市的数组
    // 这里的allValue是取出来的大数组，取第0个就是需要的内容
    self.districtArr = [[self.addressArr[self.index1] allValues][0][self.index2] allValues][0];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else if(section == 1 ){
        return 4;
    }else if(section == 2){
        return 4;
    }else if(section == 3){
        return 2;
    }else{
        return 1;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //跳转选择规格页面
    if (indexPath.section == 2 && indexPath.row == 0) {
        if (self.typeNo == nil) {
            [SVProgressHUD setMaximumDismissTimeInterval:1];
            [SVProgressHUD showErrorWithStatus:@"请选择类目"];
        }else{
            
            GoodsStandardsTableViewController *vc = [[GoodsStandardsTableViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            vc.showSexCell = NO;
            vc.typeNo = self.typeNo;
            
        }
    }
//    标签
    if (indexPath.section == 1 && indexPath.row == 2) {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        TagViewController *vc = [sb instantiateViewControllerWithIdentifier:@"tagVC"];
        [self.navigationController pushViewController:vc animated:YES];
    }
//   地址
    if (indexPath.section == 4 &&indexPath.row == 0) {
        [self showAddressView];
    }
}
#pragma mark navigation delegate
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if (![segue.identifier isEqualToString:@"addGoods"]) {
        InputViewController *vc = [segue destinationViewController];
        vc.infoStr = segue.identifier;
    }
    
}
#pragma mark - UIPickerViewDataSource Implementation
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    // Returns
    switch (component)
    {
        case 0: return self.provinceArr.count;
        case 1: return self.countryArr.count;
        case 2:return self.districtArr.count;
        default:break;
    }
    return 0;
}
#pragma mark UIPickerViewDelegate Implementation
// 点击done的时候回调
- (void)actionSheetPickerDidSucceed:(ActionSheetCustomPicker *)actionSheetPicker origin:(id)origin
{
    NSMutableString *detailAddress = [[NSMutableString alloc] init];
    if (self.index1 < self.provinceArr.count) {
        NSString *firstAddress = self.provinceArr[self.index1];
        _province = firstAddress;
        [detailAddress appendString:firstAddress];
    }
    if (self.index2 < self.countryArr.count) {
        NSString *secondAddress = self.countryArr[self.index2];
        _city = secondAddress;
        [detailAddress appendString:secondAddress];
    }
    if (self.index3 < self.districtArr.count) {
        NSString *thirfAddress = self.districtArr[self.index3];
        _region = thirfAddress;
        [detailAddress appendString:thirfAddress];
    }
    // 此界面显示
//    self.areaCell.textLabel.text = detailAddress;
    // 回调到上一个界面
    //self.myBlock(detailAddress,@[@(self.index1),@(self.index2),@(self.index3)]);
    self.shipAddress.detailTextLabel.text = detailAddress;
    self.fahuodi= detailAddress;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (component)
    {
        case 0: return self.provinceArr[row];break;
        case 1: return self.countryArr[row];break;
        case 2:return self.districtArr[row];break;
        default:break;
    }
    return nil;
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel* label = (UILabel*)view;
    if (!label)
    {
        label = [[UILabel alloc] init];
        [label setFont:[UIFont systemFontOfSize:14]];
    }
    
    NSString * title = @"";
    switch (component)
    {
        case 0: title =   self.provinceArr[row];break;
        case 1: title =   self.countryArr[row];break;
        case 2: title =   self.districtArr[row];break;
        default:break;
    }
    label.textAlignment = NSTextAlignmentCenter;
    label.text=title;
    return label;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (component)
    {
        case 0:
        {
            self.index1 = row;
            self.index2 = 0;
            self.index3 = 0;
            //            [self calculateData];
            // 滚动的时候都要进行一次数组的刷新
            [self calculateFirstData];
            [pickerView reloadComponent:1];
            [pickerView reloadComponent:2];
            [pickerView selectRow:0 inComponent:1 animated:YES];
            [pickerView selectRow:0 inComponent:2 animated:YES];
        }
            break;
            
        case 1:
        {
            self.index2 = row;
            self.index3 = 0;
            //            [self calculateData];
            [self calculateFirstData];
            [pickerView selectRow:0 inComponent:2 animated:YES];
            [pickerView reloadComponent:2];
        }
            break;
        case 2:
            self.index3 = row;
            break;
        default:break;
    }
}


- (void)configurePickerView:(UIPickerView *)pickerView
{
    pickerView.showsSelectionIndicator = NO;
}



- (NSArray *)provinceArr
{
    if (_provinceArr == nil) {
        _provinceArr = [[NSArray alloc] init];
    }
    return _provinceArr;
}
-(NSArray *)countryArr
{
    if(_countryArr == nil)
    {
        _countryArr = [[NSArray alloc] init];
    }
    return _countryArr;
}

- (NSArray *)districtArr
{
    if (_districtArr == nil) {
        _districtArr = [[NSArray alloc] init];
    }
    return _districtArr;
}

-(NSArray *)addressArr
{
    if (_addressArr == nil) {
        _addressArr = [[NSArray alloc] init];
    }
    return _addressArr;
}
-(NSString *)province{
    if (_province == nil) {
        _province = [NSString string];
    }
    return _province;
}
-(NSString *)city{
    if (_city == nil) {
        _city = [NSString string];
    }
    return _city;
}
-(NSString *)region{
    if (_region == nil) {
        _region = [NSString string];
    }
    return _region;
}

//-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.row == 0) {
//        [self showAddressView];
//        
//    }
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
